package it.pecuswap.utils;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.captcha.Captcha;
import nl.captcha.backgrounds.GradiatedBackgroundProducer;
import nl.captcha.gimpy.FishEyeGimpyRenderer;
import nl.captcha.noise.StraightLineNoiseProducer;
import nl.captcha.servlet.CaptchaServletUtil;
import nl.captcha.text.producer.DefaultTextProducer;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;

public class CaptchaAction extends ActionSupport implements
		ServletRequestAware, ServletResponseAware {

	private static final long serialVersionUID = -7188155716640643864L;
	private static final char[] charForCaptcha = { 'a', 'b', 'c', 'd', 'e',
			'f', 'g', 'h', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
			'v', 'z', 'y', 'j', 'k', 'w', 'x', '1', '2', '3', '4', '5', '6',
			'7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'L',
			'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'Z', 'Y', 'J',
			'K', 'W', 'X' };

	private HttpServletResponse response;
	private HttpServletRequest request;

	public String execute() throws IOException {
		try {
			Captcha captcha = new Captcha.Builder(200, 50)
					.addText(new DefaultTextProducer(6, charForCaptcha))
					//FIXME: solo per sviluppi
					//.addBackground(new GradiatedBackgroundProducer())
					//.gimp(new FishEyeGimpyRenderer())
					.build();
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setDateHeader("Expires", 0);
			response.setContentType("image/jpeg");
			CaptchaServletUtil.writeImage(response, captcha.getImage());
			request.getSession().setAttribute("correctAnswer", captcha.getAnswer());
		} catch (Exception e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return null;
		}
		return null;
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

}
